import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { Popconfirm, message, Button } from 'antd';
import { WifiOutlined, DisconnectOutlined, UserOutlined } from '@ant-design/icons';
import { fabric } from 'fabric';
import { setupCollaboration } from '../../coordination/SimpleCollaboration';
import { getCanvasSnapshot, updateCanvasSnapshot, updateCanvas } from '../../api/canvas';
import { apiRequest } from '../../api/utils';
import { networkStatus } from '../../utils/networkStatus';
import { CanvasUtils } from '../../utils/utils';
import Circle, { circlePool } from '../../components/graph/circle';
import Rect, { rectPool } from '../../components/graph/rect';
import Ellipse, { ellipsePool } from '../../components/graph/ellipse';
import Triangle, { trianglePool } from '../../components/graph/triangle';
import Diamond, { diamondPool } from '../../components/graph/diamond';
import Pentagon, { pentagonPool } from '../../components/graph/pentagon';
import Hexagon, { hexagonPool } from '../../components/graph/hexagon';
import Star, { starPool } from '../../components/graph/star';
import Trapezoid, { trapezoidPool } from '../../components/graph/trapezoid';
import Parallelogram, { parallelogramPool } from '../../components/graph/parallelogram';
import Arrow, { arrowPool } from '../../components/graph/arrow';
import Header from '../../components/header/header';
import LeftSide from '../../components/leftSide/leftSide';
import Brush from '../../components/graph/brush';
import Img from '../../components/graph/img';
import Text from '../../components/graph/text';
import Toolbar from '../../components/toolBar/toolBar';
import UndoRedoManager from '../../utils/undoAndRedo';
import AdvancedLazyLoader from '../../utils/advancedLazyLoader';
import canvasDataWorkerManager from '../../utils/canvasDataWorkerManager';
import renderWorkerManager from '../../utils/renderWorkerManager';

import './canvas.css';

// 创建事件委托处理器
const createEventDelegate = (handlers) => {
    return (e) => {
        // 对于鼠标事件，直接调用对应的处理器
        if (e.type === 'mousedown') {
            handlers.handleMouseDown({ e });
        } else if (e.type === 'mousemove') {
            handlers.handleMouseMove({ e });
        } else if (e.type === 'mouseup') {
            handlers.handleMouseUp({ e });
        } else {
            // 对于其他事件，保持原有的处理逻辑
            const target = e.target;
            const handler = handlers[target.dataset?.action];
            if (handler) {
                handler(e);
            }
        }
    };
};

// 创建节流函数
const throttle = (func, limit) => {
    let inThrottle;
    return function (...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => (inThrottle = false), limit);
        }
    };
};

// 创建防抖函数
const debounce = (func, wait) => {
    let timeout;
    return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
};

// 在页面标题区域添加显示连接状态和在线用户的UI
const CanvasHeader = ({
   
    handleSaveCanvas,
    navigate,
    isConnected,
    onlineUsers
}) => {
    return (
        <div className="selected-canvas-header">
            <button className="back-button" onClick={() => navigate('/')}>
                <span className="back-icon">↩️</span> 画布列表
            </button>
            <button className="save-button" onClick={handleSaveCanvas}>
                <span className="save-icon">💾</span> 保存封面
            </button>
            <button
                className="export-button"
                onClick={() => {
                    const exportEvent = new CustomEvent('export-canvas');
                    document.dispatchEvent(exportEvent);
                }}
            >
                <span className="export-icon">📤</span> 导出画布
            </button>
            <Popconfirm
                title="确认清空画布"
                description="确定要清空当前画布吗？此操作不可撤销。"
                onConfirm={() => {
                    const clearEvent = new CustomEvent('clear-canvas');
                    document.dispatchEvent(clearEvent);
                    message.success('画布已清空');
                }}
                onCancel={() => {
                    message.info('已取消操作');
                }}
                okText="确定"
                cancelText="取消"
            >
                <button className="clear-button">
                    <span className="clear-icon">🗑️</span> 清空画布
                </button>
            </Popconfirm>

            {/* 显示连接状态 */}
            <Button
                type={isConnected ? 'primary' : 'default'}
                icon={isConnected ? <WifiOutlined /> : <DisconnectOutlined />}
                style={{
                    color: isConnected ? '#52c41a' : '#ff4d4f',
                    marginLeft: '20px'
                }}
            >
                {isConnected ? '已连接' : '未连接'}
            </Button>

            {/* 显示在线用户数量 */}
            <Button icon={<UserOutlined />} style={{ marginLeft: '10px' }}>
                {onlineUsers.length}
            </Button>
        </div>
    );
};

// 创建在线用户列表组件
const OnlineUsersList = ({ users }) => {
    if (!users || users.length === 0) {
        return null;
    }

    return (
        <div
            className="online-users-list"
            style={{
                position: 'absolute',
                top: '10px',
                left: '10px',
                backgroundColor: 'rgba(255, 255, 255, 0.8)',
                padding: '10px',
                borderRadius: '4px',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                zIndex: 1000
            }}
        >
            <div style={{ fontWeight: 'bold', marginBottom: '5px' }}>在线用户 ({users.length})</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {users.map((user) => (
                    <li
                        key={user.id}
                        style={{
                            display: 'flex',
                            alignItems: 'center',
                            marginBottom: '3px',
                            color: user.isCurrentUser ? '#1890ff' : 'inherit'
                        }}
                    >
                        <div
                            style={{
                                width: '10px',
                                height: '10px',
                                borderRadius: '50%',
                                backgroundColor: user.color,
                                marginRight: '5px'
                            }}
                        ></div>
                        {user.name} {user.isCurrentUser ? '(你)' : ''}
                    </li>
                ))}
            </ul>
        </div>
    );
};

const Canvas = () => {
    // const commandManagerRef = useRef(null);
    const location = useLocation();
    const routeTitle = location.state?.title;
    // 对象池数组
    const { id } = useParams();
    const hasFetchData = useRef(false);

    const [isOnline, setIsOnline] = useState(networkStatus.isOnline());
    const navigate = useNavigate();
    const canvasRef = useRef(null);
    const fabricRef = useRef(null);
    const brushRef = useRef(null);
    const fileInputRef = useRef(null);
    const handleKeyDownRef = useRef(null); // 存储键盘事件处理函数的引用
    const [currentTool, setCurrentTool] = useState(null); // 跟踪当前选中的工具
    const [selectedObjects, setSelectedObjects] = useState([]);
    const [canvasData, setCanvasData] = useState(null); // 保存画布数据
    const [canvasTitle, setCanvasTitle] = useState(routeTitle || ''); // 使用路由传递的title作为初始值
    const [loading, setLoading] = useState(true); // 加载状态
    const [isEditing, setIsEditing] = useState(false); // 添加标题编辑状态
    const canvasContainerRef = useRef(null);

    const [isConnected, setIsConnected] = useState(false);
    const [onlineUsers, setOnlineUsers] = useState([]);
    const collaborationRef = useRef(null);
    const [canvasReady, setCanvasReady] = useState(false);

    // 维护清空画布防抖相关的引用
    const lastClearTimeRef = useRef(0);
    const clearDebounceTimeoutRef = useRef(null);
    const clearMessageDebounceRef = useRef(null);

    const undoRedoManagerRef = useRef(null);
    const lazyLoaderRef = useRef(null);

    // 处理标题更改
    const onTitleChange = useCallback(
        (newTitle, isEditMode, isBlur) => {
            // 如果传入了isEditMode参数，则切换编辑状态
            if (isEditMode !== undefined) {
                setIsEditing(isEditMode);
                return;
            }

            // 处理空标题，使用默认值
            const processedTitle = newTitle || '';

            // 使用函数式更新确保状态正确
            setCanvasTitle(processedTitle);
            // 只有在失去焦点时才退出编辑模式并保存标题
            if (isBlur) {
                setIsEditing(false);
            }
        },
        [id]
    );
    // 初始化Yjs协作 - 仅在画布准备就绪后执行
    useEffect(() => {
        if (!canvasReady || !fabricRef.current) {
            return;
        }

        const initializeCollaboration = () => {
            try {
                const username = localStorage.getItem('username') || 'anonymous';
                // 先创建 UndoRedoManager
                undoRedoManagerRef.current = new UndoRedoManager(
                    fabricRef.current,
                    null // 暂时传入 null，后续会更新
                );
                // 然后设置协作
                collaborationRef.current = setupCollaboration(
                    fabricRef.current,
                    id,
                    username,
                    undoRedoManagerRef
                );
                // 更新 UndoRedoManager 的协作引用

                undoRedoManagerRef.current.setCollaboration(collaborationRef.current);
                setTimeout(() => {
                    undoRedoManagerRef.current.clearHistory();
                }, 500);

                const handleConnectionStatus = (event) => {
                    if (event.detail && event.detail.status) {
                        const status = event.detail.status;
                        setIsConnected(status === 'connected');

                        if (status === 'connected') {
                        } else if (status === 'disconnected') {
                            message.warning('已断开协作服务器连接');
                        }
                    }
                };

                // 监听远程清空画布事件
                const handleRemoteCanvasClear = () => {
                    // 获取当前时间
                    const currentTime = Date.now();

                    // 如果距离上次清空时间小于2秒，忽略此次事件
                    if (currentTime - lastClearTimeRef.current < 2000) {
                        return;
                    }

                    // 更新上次清空时间
                    lastClearTimeRef.current = currentTime;

                    // 清除之前的防抖定时器
                    if (clearDebounceTimeoutRef.current) {
                        clearTimeout(clearDebounceTimeoutRef.current);
                    }

                    // 设置防抖定时器，确保短时间内只执行一次
                    clearDebounceTimeoutRef.current = setTimeout(() => {
                        // 重置历史记录
                        historyRef.current = {
                            undoStack: [],
                            redoStack: [],
                            canvasState: null
                        };

                        // 清空对象池引用
                        setPoolArray([]);

                        // 保存初始空白状态
                        setTimeout(() => {
                            if (fabricRef.current) {
                                const json = JSON.stringify(fabricRef.current.toJSON(['id']));
                                historyRef.current.undoStack.push(json);
                            }
                        }, 50);

                        // 防抖处理消息提示
                        if (clearMessageDebounceRef.current) {
                            clearTimeout(clearMessageDebounceRef.current);
                        }

                        clearMessageDebounceRef.current = setTimeout(() => {
                            message.info('画布已被其他用户清空');
                        }, 300);
                    }, 200);
                };

                // 添加自定义事件监听器
                document.addEventListener('collaboration-status-changed', handleConnectionStatus);
                document.addEventListener('canvas-cleared-remotely', handleRemoteCanvasClear);
                // 立即手动检查连接状态
                if (collaborationRef.current && collaborationRef.current.checkConnection) {
                    collaborationRef.current.checkConnection();
                }

                // 3秒后再次手动检查连接状态
                setTimeout(() => {
                    if (collaborationRef.current && collaborationRef.current.checkConnection) {
                        collaborationRef.current.checkConnection();
                    }
                }, 3000);

                // 监听用户列表更新
                document.addEventListener('userListUpdated', handleUserListUpdate);

                // 清理函数
                return () => {
                    document.removeEventListener(
                        'collaboration-status-changed',
                        handleConnectionStatus
                    );
                    document.removeEventListener('userListUpdated', handleUserListUpdate);
                    document.removeEventListener(
                        'canvas-cleared-remotely',
                        handleRemoteCanvasClear
                    );

                    // 断开WebSocket连接
                    if (collaborationRef.current && collaborationRef.current.wsProvider) {
                        collaborationRef.current.wsProvider.disconnect();
                    }
                };
            } catch (error) {
                console.error('初始化协作失败:', error);
                message.error('初始化协作失败: ' + error.message);
            }
        };

        const cleanup = initializeCollaboration();

        return () => {
            if (cleanup) {
                console.log('执行协作清理函数...');
                cleanup();
            }
        };
    }, [canvasReady]);
    // 处理用户列表更新的函数
    const handleUserListUpdate = (event) => {
        if (event.detail && event.detail.users) {
            setOnlineUsers(event.detail.users);
        }
    };

    // 添加对象池数组状态
    const [poolArray, setPoolArray] = useState([]);

    const fetchCanvasData = async () => {
        if (!id) return;

        try {
            setLoading(true);

            // 检查token是否存在
            const token = localStorage.getItem('token');
            if (!token) {
                console.error('未找到认证token');
                message.error('请先登录');
                return;
            }

            const response = await apiRequest(() => getCanvasSnapshot(id));

            if (response && response.code === 200) {
                // 检查数据是否为空
                if (!response.data) {
                    console.warn('画布数据为空');
                    message.warning('画布数据为空');
                    return;
                }

                // 检查数据是否为字符串，如果是则尝试解析
                let canvasData = response.data;
                if (typeof canvasData === 'string') {
                    try {
                        // 使用 Worker 反序列化数据
                        canvasData = await canvasDataWorkerManager.deserialize(canvasData);
                    } catch (parseError) {
                        console.error('解析画布数据失败:', parseError);
                        message.error('画布数据格式错误');
                        return;
                    }
                }

                // 过滤掉cursor对象和其他无效对象
                if (canvasData.objects && Array.isArray(canvasData.objects)) {
                    canvasData.objects = canvasData.objects.filter((obj) => {
                        if (obj.type === 'cursor') {
                            return false;
                        }
                        return obj && typeof obj === 'object';
                    });

                    // 确保每个对象都有正确的类名和ID
                    canvasData.objects = canvasData.objects.map((obj) => {
                        if (!obj.id) {
                            obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                        }
                        return obj;
                    });
                }

                setCanvasData(canvasData);

                // 加载到fabric画布
                if (fabricRef.current) {
                    try {
                        // 清空当前画布
                        fabricRef.current.clear();

                        // 加载画布数据
                        fabricRef.current.loadFromJSON(canvasData, () => {
                            // 初始化懒加载器
                            if (!lazyLoaderRef.current) {
                                lazyLoaderRef.current = new AdvancedLazyLoader(
                                    fabricRef.current,
                                    fabricRef.current.getObjects(),
                                    {
                                        viewportMargin: 200,
                                        preloadMargin: 300,
                                        batchSize: 10
                                    }
                                );
                            } else {
                                // 更新懒加载器的对象列表
                                lazyLoaderRef.current.updateObjects(fabricRef.current.getObjects());
                            }

                            // 恢复缩放比例
                            if (canvasData.zoom) {
                                console.log('恢复缩放比例:', canvasData.zoom);
                                fabricRef.current.setZoom(canvasData.zoom);
                                setZoom(canvasData.zoom);
                                fabricRef.current.requestRenderAll();
                            }

                            // 同步到远程数据
                            if (collaborationRef.current?.sharedObjects) {
                                const sharedObjects = collaborationRef.current.sharedObjects;
                                const userId = localStorage.getItem('userId') || 'anonymous';

                                fabricRef.current.getObjects().forEach((obj) => {
                                    if (obj.type !== 'cursor') {
                                        if (!obj.id) {
                                            obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                                        }

                                        const serializedObj = JSON.stringify({
                                            id: obj.id,
                                            type: obj.type,
                                            objData: obj.toJSON(['id']),
                                            timestamp: Date.now(),
                                            userId: userId
                                        });
                                        sharedObjects.set(obj.id, serializedObj);
                                    }
                                });
                            }

                            fabricRef.current.requestRenderAll();
                        });
                    } catch (error) {
                        console.error('加载画布数据到Fabric失败:', error);
                        message.error('加载画布数据失败: ' + error.message);
                    }
                } else {
                    console.warn('Fabric画布引用不存在');
                }
            } else {
                console.warn('获取画布数据失败或数据格式不正确:', response);
                message.warning('获取画布数据失败: ' + (response?.msg || '未知错误'));
            }
        } catch (error) {
            console.error('获取画布数据错误:', error);
            message.error('获取画布数据失败: ' + (error.message || '未知错误'));
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        const removeNetworkListener = networkStatus.addListener(setIsOnline);

        // 只发送一次获取快照请求
        if (!hasFetchData.current) {
            fetchCanvasData();
            hasFetchData.current = true;
        }

        // 初始化画布时启用渲染优化
        if (fabricRef.current) {
            const canvas = fabricRef.current;
            // 启用渲染优化
            canvas.renderOnAddRemove = true;
            canvas.partialUpdate = true;
            // 启用硬件加速
            canvas.enableRetinaScaling = true;
            // 设置渲染策略
            canvas.renderOnAddRemove = true;
            // 优化性能
            canvas.skipTargetFind = false;
            canvas.skipOffscreen = true;
            // 设置渲染帧率
            canvas.setZoom(1);
            canvas.setWidth(canvas.width);
            canvas.setHeight(canvas.height);
        }

        return () => {
            removeNetworkListener();
        };
    }, [id]);

    // 保存画布
    const handleSaveCanvas = useCallback(async () => {
        if (!fabricRef.current || !id) {
            message.error('无法保存画布');
            return;
        }

        try {
            // 检查画布是否有效
            const canvas = fabricRef.current;
            if (!canvas.getContext()) {
                console.error('画布上下文无效');
                message.error('画布状态异常，请刷新页面重试');
                return;
            }

            try {
                // 获取画布数据
                const canvasData = fabricRef.current.toJSON(['id']);
                // 添加缩放比例到快照数据
                canvasData.zoom = fabricRef.current.getZoom();

                // 使用 Worker 序列化数据
                // const serializedData = await canvasDataWorkerManager.serialize(canvasData);
                
                // 检查序列化是否成功
                // if (!serializedData) {
                //     throw new Error('序列化数据失败');
                // }

                // 保存当前的视口变换和缩放
                const currentViewport = {
                    zoom: fabricRef.current.getZoom(),
                    viewportTransform: [...fabricRef.current.viewportTransform]
                };

                // 创建临时画布用于生成缩略图
                const tempCanvas = document.createElement('canvas');
                const tempCtx = tempCanvas.getContext('2d');
                
                if (!tempCtx) {
                    throw new Error('无法创建临时画布上下文');
                }

                // 设置临时画布尺寸
                const originalWidth = fabricRef.current.getWidth();
                const originalHeight = fabricRef.current.getHeight();
                const targetWidth = originalWidth;
                const targetHeight = originalHeight;

                const aspectRatio = originalWidth / originalHeight;
                const targetAspectRatio = targetWidth / targetHeight;

                let finalWidth, finalHeight;
                if (aspectRatio > targetAspectRatio) {
                    finalWidth = targetWidth;
                    finalHeight = targetWidth / aspectRatio;
                } else {
                    finalHeight = targetHeight;
                    finalWidth = targetHeight * aspectRatio;
                }

                tempCanvas.width = Math.round(finalWidth);
                tempCanvas.height = Math.round(finalHeight);

                // 临时设置画布状态
                const originalZoom = fabricRef.current.getZoom();
                const originalViewportTransform = [...fabricRef.current.viewportTransform];

                try {
                    // 设置临时视口变换
                    fabricRef.current.setViewportTransform([1, 0, 0, 1, 0, 0]);
                    fabricRef.current.setZoom(1);

                    // 渲染到临时画布
                    fabricRef.current.requestRenderAll();
                    
                    // 生成缩略图
                    const thumbnailDataURL = fabricRef.current.toDataURL({
                        format: 'png',
                        quality: 1.0,
                        width: Math.round(finalWidth),
                        height: Math.round(finalHeight),
                        multiplier: 2.0,
                        enableRetinaScaling: true,
                        withoutTransforms: true
                    });

                    // 恢复原始视口变换和缩放
                    fabricRef.current.setViewportTransform(originalViewportTransform);
                    fabricRef.current.setZoom(originalZoom);
                    fabricRef.current.requestRenderAll();

                    // 保存画布快照
                    // const snapshotResponse = await apiRequest(() =>
                    //     updateCanvasSnapshot(id, serializedData)
                    // );

                    // 更新画布封面图片
                    const updateResponse = await apiRequest(() =>
                        updateCanvas(id, canvasTitle, thumbnailDataURL, fabricRef.current.getZoom())
                    );
                    if (updateResponse?.code === 200) {
                        message.success('画布封面保存成功');
                    } else {
                        message.error('画布封面保存失败: ' + updateResponse?.msg);
                    }

                    // if (snapshotResponse?.code === 200 && updateResponse?.code === 200) {
                    //     message.success('画布保存成功');

                    //     // 更新远程数据
                    //     if (collaborationRef.current?.sharedObjects) {
                    //         console.log('开始同步远程数据...');
                    //         const sharedObjects = collaborationRef.current.sharedObjects;
                    //         const userId = localStorage.getItem('userId') || 'anonymous';

                    //         // 添加所有本地对象到远程
                    //         const objects = canvas.getObjects();
                    //         objects.forEach((obj) => {
                    //             if (obj.type !== 'cursor') {
                    //                 if (!obj.id) {
                    //                     obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                    //                 }

                    //                 const serializedObj = JSON.stringify({
                    //                     id: obj.id,
                    //                     type: obj.type,
                    //                     objData: obj.toJSON(['id']),
                    //                     timestamp: Date.now(),
                    //                     userId: userId
                    //                 });
                    //                 sharedObjects.set(obj.id, serializedObj);
                    //             }
                    //         });

                    //         console.log('远程数据同步完成');
                    //     }
                    // } else {
                    //     message.error(
                    //         '保存失败: ' + (snapshotResponse?.msg || updateResponse?.msg || '未知错误')
                    //     );
                    // }
                } finally {
                    // 确保恢复原始状态
                    fabricRef.current.setViewportTransform(originalViewportTransform);
                    fabricRef.current.setZoom(originalZoom);
                    fabricRef.current.requestRenderAll();
                }
            } catch (error) {
                console.error('保存失败:', error);
                message.error('保存失败: ' + error.message);
            }
        } catch (error) {
            console.error('保存失败:', error);
            message.error('保存失败: ' + error.message);
        }
    }, [id, canvasTitle]);

    // 在组件初始化时记录日志
    useEffect(() => {
        console.log('初始化poolArray:', poolArray);
    }, [poolArray]);

    /**
     * 处理删除画布上选中的对象
     */
    const handleDeleteObject = () => {
        const fabricCanvas = fabricRef.current;
        if (!fabricCanvas || !fabricCanvas.getActiveObject) return;

        try {
            const activeObject = fabricCanvas.getActiveObject();
            if (!activeObject) return;

            // 先取消选中状态
            fabricCanvas.discardActiveObject();

            // 释放对象到对应的对象池的函数
            const releaseToPool = (obj) => {
                try {
                    console.log('🔍 尝试释放对象到对象池:', obj.type);

                    // 根据对象类型释放到对应的对象池
                    if (obj instanceof Circle) {
                        console.log('♻️ 释放Circle对象到对象池');
                        circlePool.release(obj);
                    } else if (obj instanceof Rect) {
                        console.log('♻️ 释放Rect对象到对象池');
                        rectPool.release(obj);
                    } else if (obj instanceof Ellipse) {
                        console.log('♻️ 释放Ellipse对象到对象池');
                        ellipsePool.release(obj);
                    } else if (obj instanceof Triangle) {
                        console.log('♻️ 释放Triangle对象到对象池');
                        trianglePool.release(obj);
                    } else if (obj instanceof Diamond) {
                        console.log('♻️ 释放Diamond对象到对象池');
                        diamondPool.release(obj);
                    } else if (obj instanceof Pentagon) {
                        console.log('♻️ 释放Pentagon对象到对象池');
                        pentagonPool.release(obj);
                    } else if (obj instanceof Hexagon) {
                        console.log('♻️ 释放Hexagon对象到对象池');
                        hexagonPool.release(obj);
                    } else if (obj instanceof Star) {
                        console.log('♻️ 释放Star对象到对象池');
                        starPool.release(obj);
                    } else if (obj instanceof Trapezoid) {
                        console.log('♻️ 释放Trapezoid对象到对象池');
                        trapezoidPool.release(obj);
                    } else if (obj instanceof Parallelogram) {
                        console.log('♻️ 释放Parallelogram对象到对象池');
                        parallelogramPool.release(obj);
                    } else if (obj instanceof Arrow) {
                        console.log('♻️ 释放Arrow对象到对象池');
                        arrowPool.release(obj);
                    }
                } catch (error) {
                    console.error('❌ 释放对象到对象池失败:', error);
                }
            };

            // 处理多选情况
            if (activeObject.type === 'activeSelection') {
                // 如果是多选组，删除组内所有对象
                activeObject.forEachObject((obj) => {
                    if (fabricCanvas.getObjects().includes(obj)) {
                        // 先释放到对象池
                        releaseToPool(obj);
                        // 然后从画布中移除
                        fabricCanvas.remove(obj);
                        // 发送删除通知
                        collaborationRef.current.handleDelete(obj.id);
                    }
                });
                console.log('多选对象已删除并释放到对象池');
            } else {
                // 单个对象删除
                if (fabricCanvas.getObjects().includes(activeObject)) {
                    // 先释放到对象池
                    releaseToPool(activeObject);
                    // 然后从画布中移除
                    fabricCanvas.remove(activeObject);
                    // 发送删除通知
                    collaborationRef.current.handleDelete(activeObject.id);
                    console.log('对象已删除并释放到对象池');
                }
            }

            // 调用协作删除处理
            if (collaborationRef.current && collaborationRef.current.handleDelete) {
                collaborationRef.current.handleDelete();
            }

            // 延迟渲染确保状态稳定
            setTimeout(() => {
                throttledRenderAll();
            }, 0);
        } catch (error) {
            console.error('删除对象错误:', error);
            throttledRenderAll();
        }
    };

    // 添加历史记录状态
    const historyRef = useRef({
        undoStack: [], // 撤销栈
        redoStack: [], // 重做栈
        canvasState: null
    });

    // 处理清空画布
    const handleClearCanvas = useCallback(() => {
        const fabricCanvas = fabricRef.current;
        if (!fabricCanvas) return;

        console.log('🧹 清空画布开始');

        // 广播清空画布事件
        if (collaborationRef.current && collaborationRef.current.broadcastClearCanvas) {
            collaborationRef.current.broadcastClearCanvas();
            console.log('已广播清空画布事件');
        }

        // 先将图形对象释放回对象池
        const objects = fabricCanvas.getObjects();
        console.log('🧹 画布上的对象数量:', objects.length);

        // 记录对象池大小变化
        console.log('🧹 清空前对象池大小:', circlePool.pool ? circlePool.pool.length : 'unknown');

        // 遍历画布上的所有对象
        objects.forEach((obj) => {
            console.log('🔍 检查对象:', obj.type, 'isCircle:', obj instanceof Circle);

            // 根据对象类型释放到对应的对象池
            try {
                // 圆形
                if (obj instanceof Circle) {
                    console.log('♻️ 释放Circle对象到对象池');
                    circlePool.release(obj);
                }
                // 矩形
                else if (obj instanceof Rect) {
                    console.log('♻️ 释放Rect对象到对象池');
                    rectPool.release(obj);
                }
                // 椭圆
                else if (obj instanceof Ellipse) {
                    console.log('♻️ 释放Ellipse对象到对象池');
                    ellipsePool.release(obj);
                }
                // 三角形
                else if (obj instanceof Triangle) {
                    console.log('♻️ 释放Triangle对象到对象池');
                    trianglePool.release(obj);
                }
                // 菱形
                else if (obj instanceof Diamond) {
                    console.log('♻️ 释放Diamond对象到对象池');
                    diamondPool.release(obj);
                }
                // 五边形
                else if (obj instanceof Pentagon) {
                    console.log('♻️ 释放Pentagon对象到对象池');
                    pentagonPool.release(obj);
                }
                // 六边形
                else if (obj instanceof Hexagon) {
                    console.log('♻️ 释放Hexagon对象到对象池');
                    hexagonPool.release(obj);
                }
                // 星形
                else if (obj instanceof Star) {
                    console.log('♻️ 释放Star对象到对象池');
                    starPool.release(obj);
                }
                // 梯形
                else if (obj instanceof Trapezoid) {
                    console.log('♻️ 释放Trapezoid对象到对象池');
                    trapezoidPool.release(obj);
                }
                // 平行四边形
                else if (obj instanceof Parallelogram) {
                    console.log('♻️ 释放Parallelogram对象到对象池');
                    parallelogramPool.release(obj);
                }
                // 箭头
                else if (obj instanceof Arrow) {
                    console.log('♻️ 释放Arrow对象到对象池');
                    arrowPool.release(obj);
                }
            } catch (error) {
                console.error('❌ 释放对象失败:', error);
            }
        });

        console.log('🧹 清空后对象池大小:', circlePool.pool ? circlePool.pool.length : 'unknown');

        // 清空画布
        fabricCanvas.clear();

        // 重置画布配置
        fabricCanvas.setBackgroundColor('#ffffff', fabricCanvas.requestRenderAll.bind(fabricCanvas));

        // 清空撤销/重做栈
        if (undoRedoManagerRef.current) {
            undoRedoManagerRef.current.clearHistory();
            console.log('已清空撤销/重做栈');
        }

        // 重新渲染画布
        throttledRenderAll();
    }, []);

    useEffect(() => {
        // 确保在组件挂载后才初始化画布
        const canvas = canvasRef.current;
        if (!canvas) return;

        // 防止重复初始化
        if (fabricRef.current) {
            fabricRef.current.dispose();
            fabricRef.current = null;
        }

        // 获取容器尺寸
        const container = canvas.parentElement;
        const canvasWidth = container.clientWidth;
        const canvasHeight = container.clientHeight;

        console.log('Canvas dimensions:', canvasWidth, canvasHeight);

        // 创建 fabric 画布实例
        const fabricCanvas = new fabric.Canvas(canvas, {
            width: canvasWidth,
            height: canvasHeight,
            backgroundColor: '#ffffff',
            selection: true, // 允许多选
            preserveObjectStacking: true,
            // 禁用所有网格相关功能
            grid: false,
            enableRetinaScaling: false,
            enableGrid: false,
            backgroundVpt: false,
            snapToGrid: false,
            snapToAngle: false,
            showGrid: false
        });

        // 确保画布上下文已创建
        if (!fabricCanvas.getContext()) {
            console.error('Failed to create canvas context');
            return;
        }

        // 添加画布拖拽功能
        let isDragging = false;
        let lastPosX = 0;
        let lastPosY = 0;

        // 创建事件处理器对象
        const eventHandlers = {
            // 键盘事件处理
            handleKeyDown: throttle((e) => {
                try {
                    if (e.key === 'b' || e.key === 'B') {
                        if (fabricCanvas.isDrawingMode) {
                            brush.stop();
                            setCurrentTool(null);
                        } else {
                            brush.start();
                            setCurrentTool('brush');
                        }
                    } else if (e.key === 'z' && e.ctrlKey && !e.shiftKey) {
                        e.preventDefault();
                        if (undoRedoManagerRef.current) {
                            undoRedoManagerRef.current.undo();
                        }
                    } else if (
                        (e.key === 'y' && e.ctrlKey) ||
                        (e.key === 'z' && e.ctrlKey && e.shiftKey)
                    ) {
                        e.preventDefault();
                        if (undoRedoManagerRef.current) {
                            undoRedoManagerRef.current.redo();
                        }
                    } else if (e.key === 'Escape') {
                        brush.stop();
                        setCurrentTool(null);
                    } else if (e.key === 'Delete') {
                        handleDeleteObject();
                    }
                } catch (error) {
                    console.error('键盘事件处理错误:', error);
                }
            }, 100),

            // 鼠标事件处理
            handleMouseDown: throttle((opt) => {
                const e = opt.e;
                // 如果按住Ctrl键，启用多选模式
                if (e.ctrlKey) {
                    isDragging = false;
                    fabricCanvas.selection = true;
                    fabricCanvas.defaultCursor = 'default';
                    return;
                }

                // 如果有选中对象，禁用画布拖拽
                if (opt.target || fabricCanvas.getActiveObject()) {
                    isDragging = false;
                    fabricCanvas.selection = true;
                    fabricCanvas.defaultCursor = 'default';
                    return;
                }

                // 只有在没有选中对象且没有按住Ctrl键时，才允许画布拖拽
                isDragging = true;
                lastPosX = e.clientX;
                lastPosY = e.clientY;
                fabricCanvas.selection = false;
                fabricCanvas.defaultCursor = 'move';
            }, 50),

            handleMouseMove: throttle((opt) => {
                // 如果有选中对象，禁用画布拖拽
                if (opt.target || fabricCanvas.getActiveObject()) {
                    isDragging = false;
                    return;
                }

                // 只有在没有选中对象且处于拖拽状态时才允许画布拖拽
                if (isDragging) {
                    const e = opt.e;
                    const deltaX = e.clientX - lastPosX;
                    const deltaY = e.clientY - lastPosY;

                    const vpt = fabricCanvas.viewportTransform;
                    vpt[4] += deltaX;
                    vpt[5] += deltaY;

                    fabricCanvas.requestRenderAll();

                    lastPosX = e.clientX;
                    lastPosY = e.clientY;
                }
            }, 16),

            handleMouseUp: throttle(() => {
                if (isDragging) {
                    isDragging = false;
                    fabricCanvas.selection = true;
                    fabricCanvas.defaultCursor = 'default';
                }
            }, 50),

            // 对象事件处理
            handleObjectAdded: debounce((e) => {
                if (
                    !e.target ||
                    e.target.type === 'cursor' ||
                    collaborationRef.current?.isLoadingCanvas ||
                    collaborationRef.current?.isUpdatingFromRemote
                ) {
                    return;
                }

                if (e.target._commandProcessed) {
                    return;
                }

                if (
                    undoRedoManagerRef.current &&
                    !undoRedoManagerRef.current.isRestoringState &&
                    !undoRedoManagerRef.current.isUndoRedoOperation
                ) {
                    undoRedoManagerRef.current.saveState();
                }
            }, 100),

            handleObjectModified: debounce((e) => {
                if (
                    e.target?.type === 'cursor' ||
                    e.target?.id?.includes('cursor') ||
                    e.target?.id?.includes('temp')
                ) {
                    return;
                }

                if (e.target && !e.target._isMoving) {
                    undoRedoManagerRef.current.saveState();
                }
            }, 100),

            handleObjectRemoved: debounce((e) => {
                if (!e.target || e.target.type === 'cursor' || e.target.id?.includes('cursor'))
                    return;
                if (
                    undoRedoManagerRef.current &&
                    !undoRedoManagerRef.current.isRestoringState &&
                    !undoRedoManagerRef.current.isUndoRedoOperation
                ) {
                    undoRedoManagerRef.current.saveState();
                }
            }, 100)
        };

        // 使用事件委托设置事件监听
        const canvasContainer = canvasContainerRef.current;
        if (canvasContainer) {
            const delegate = createEventDelegate(eventHandlers);
            canvasContainer.addEventListener('mousedown', delegate);
            canvasContainer.addEventListener('mousemove', delegate);
            canvasContainer.addEventListener('mouseup', delegate);
        }

        // 设置键盘事件监听
        document.addEventListener('keydown', eventHandlers.handleKeyDown);

        // 设置画布事件监听
        fabricCanvas.on('object:added', eventHandlers.handleObjectAdded);
        fabricCanvas.on('object:modified', eventHandlers.handleObjectModified);
        fabricCanvas.on('object:removed', eventHandlers.handleObjectRemoved);

        fabricRef.current = fabricCanvas;

        // 初始化缩放功能
        CanvasUtils.initZoom(fabricCanvas);

        // 设置画布准备就绪的状态，触发协同初始化
        console.log('设置canvasReady为true，准备初始化协同编辑');
        setCanvasReady(true);
        // 监听画布缩放事件
        fabricCanvas.on('mouse:wheel', (opt) => {
            const currentZoom = fabricCanvas.getZoom();
            setZoom(currentZoom);
        });

        fabricCanvas.on('mouse:wheel:alt', (opt) => {
            const currentZoom = fabricCanvas.getZoom();
            setZoom(currentZoom);
        });

        // 监听导出画布的自定义事件
        const handleExportCanvas = () => {
            exportCanvas();
        };
        document.addEventListener('export-canvas', handleExportCanvas);

        // 添加选择对象改变的事件处理
        fabricCanvas.on('selection:created', handleSelectionChange);
        fabricCanvas.on('selection:updated', handleSelectionChange);
        fabricCanvas.on('selection:cleared', () => setSelectedObjects([]));

        function handleSelectionChange(options) {
            // 检查选中的对象是否为图片
            const selectedObjs = options.selected || [];
            const hasImages = selectedObjs.some((obj) => obj.type === 'image' || obj._element);

            // 如果选中的包含图片，不更新选中对象状态（这样就不会显示工具栏）
            if (hasImages) {
                console.log('图片被选中，不显示工具栏');
                return;
            }

            // 更新选中对象数组
            if (selectedObjs.length > 0) {
                setSelectedObjects(selectedObjs);
            } else if (options.target) {
                setSelectedObjects([options.target]);

                // 确保选中对象的坐标正确更新
                if (options.target.type === 'activeSelection' || options.target.type === 'group') {
                    // 延迟一帧执行，确保DOM更新后再计算坐标
                    requestAnimationFrame(() => {
                        if (options.target && typeof options.target.setCoords === 'function') {
                            options.target.setCoords();
                            fabricCanvas.requestRenderAll();
                        }
                    });
                }
            }
        }

        // 创建画笔实例
        const brush = new Brush(fabricCanvas, {
            width: 2,
            color: '#e74c3c' // 红色画笔
        });
        console.log('Brush initialized:', brush);
        console.log('setMode exists:', typeof brush.setMode === 'function');
        brushRef.current = brush;

        // 保存初始状态
        setTimeout(() => {
            if (fabricRef.current) {
                const initialJson = JSON.stringify(fabricRef.current.toJSON(['id']));
                historyRef.current.undoStack = [initialJson];
                historyRef.current.redoStack = [];
                console.log('初始状态已保存，撤销栈长度=', historyRef.current.undoStack.length);
            }
        }, 200);

        // 添加对象添加、修改、删除事件监听
        fabricCanvas.on('object:added', (e) => {
            // 忽略光标对象和远程更新
            if (
                !e.target ||
                e.target.type === 'cursor' ||
                collaborationRef.current?.isLoadingCanvas ||
                collaborationRef.current?.isUpdatingFromRemote
            ) {
                return;
            }

            // 如果对象是通过命令添加的，跳过处理
            if (e.target._commandProcessed) {
                console.log('对象是通过命令添加的，跳过创建命令');
                return;
            }

            // 保存状态到撤销栈
            if (
                undoRedoManagerRef.current &&
                !undoRedoManagerRef.current.isRestoringState &&
                !undoRedoManagerRef.current.isUndoRedoOperation
            ) {
                undoRedoManagerRef.current.saveState();
            }
        });

        fabricCanvas.on('object:modified', (e) => {
            // 忽略临时对象和光标
            if (
                e.target?.type === 'cursor' ||
                e.target?.id?.includes('cursor') ||
                e.target?.id?.includes('temp')
            ) {
                return;
            }

            // 只有在对象真正发生变化时才保存状态
            if (e.target && !e.target._isMoving) {
                undoRedoManagerRef.current.saveState();
            }
        });

        fabricCanvas.on('object:removed', (e) => {
            if (!e.target || e.target.type === 'cursor' || e.target.id?.includes('cursor')) return;
            if (
                undoRedoManagerRef.current &&
                !undoRedoManagerRef.current.isRestoringState &&
                !undoRedoManagerRef.current.isUndoRedoOperation
            ) {
                undoRedoManagerRef.current.saveState();
            }
        });

        // 监听对象移动开始
        fabricCanvas.on('object:moving', (e) => {
            if (e.target) {
                e.target._isMoving = true;
            }
        });

        // 监听对象移动结束
        fabricCanvas.on('object:modified', (e) => {
            if (e.target) {
                e.target._isMoving = false;
                // 只有在移动结束时才保存状态
                undoRedoManagerRef.current.saveState();
            }
        });

        // 添加键盘事件监听
        document.addEventListener('keydown', eventHandlers.handleKeyDown);

        // 添加测试局部文本样式的示例
        const testText = new fabric.IText('测试文本', {
            left: canvasWidth / 2 - 150,
            top: canvasHeight / 2 + 150,
            fontFamily: 'Arial',
            fontSize: 20,
            fill: '#333',
            editable: true,
            styles: {
                0: {
                    // 第0行
                    0: { fill: 'red', fontWeight: 'bold' }, // "这"
                    1: { fill: 'blue' }, // "是"
                    2: { fill: 'green', fontStyle: 'italic' }, // "测"
                    3: { fill: 'purple', textBackgroundColor: 'yellow' } // "试"
                }
            }
        });

        // 注册编辑结束事件，打印样式信息
        testText.on('editing:exited', () => {
            console.log('Text editing exited, styles:', testText.styles);
        });

        // 监听鼠标点击事件，便于测试局部样式
        fabricCanvas.on('mouse:down', (options) => {
            if (options.target && options.target.type === 'i-text') {
                console.log('Text clicked, current styles:', options.target.styles);
            }
        });

        // 窗口大小调整时重设画布大小
        const handleResize = () => {
            const newWidth = container.clientWidth;
            const newHeight = container.clientHeight;

            fabricCanvas.setDimensions({
                width: newWidth,
                height: newHeight
            });
            fabricCanvas.requestRenderAll();
        };

        window.addEventListener('resize', handleResize);

        // 添加清空画布事件监听
        document.addEventListener('clear-canvas', handleClearCanvas);

        // 添加远程命令处理
        const handleRemoteCanvasCommand = (event) => {
            try {
                const commandInfo = event.detail;

                if (commandInfo.type === 'command:undo' || commandInfo.type === 'command:redo') {
                    const action = commandInfo.type.split(':')[1];
                    // 传递完整的命令数据，包括状态和栈信息
                    undoRedoManagerRef.current.handleRemoteUndoRedo(action, {
                        state: commandInfo.state,
                        stackInfo: commandInfo.stackInfo
                    });
                }
            } catch (error) {
                console.error('处理远程命令时出错:', error);
            }
        };

        document.addEventListener('remote-canvas-command', handleRemoteCanvasCommand);

        // 清理事件监听
        return () => {
            fabricCanvas.off('object:modified');
            fabricCanvas.off('object:added');
            fabricCanvas.off('object:removed');
            document.removeEventListener('keydown', eventHandlers.handleKeyDown);
            document.removeEventListener('export-canvas', handleExportCanvas);
            document.removeEventListener('clear-canvas', handleClearCanvas);
            document.removeEventListener('remote-canvas-command', handleRemoteCanvasCommand);
            window.removeEventListener('resize', handleResize);

            // 销毁画布
            if (fabricRef.current) {
                try {
                    // 移除所有对象
                    fabricRef.current.getObjects().forEach((obj) => {
                        fabricRef.current.remove(obj);
                    });

                    // 清除画布
                    fabricRef.current.clear();

                    // 销毁画布实例
                    fabricRef.current.dispose();
                    fabricRef.current = null;
                } catch (error) {
                    console.error('Error disposing canvas:', error);
                }
            }

            // 清理协作
            if (collaborationRef.current) {
                const { wsProvider } = collaborationRef.current;
                if (wsProvider) {
                    wsProvider.disconnect();
                }
            }

            // 移除事件监听器
            document.removeEventListener('userListUpdated', handleUserListUpdate);
            document.removeEventListener('collaboration-status-changed', () => {});
        };
    }, []);

    // 处理侧边栏点击图形的事件
    const handleShapeClick = (shape) => {
        const fabricCanvas = fabricRef.current;
        if (!fabricCanvas) return;

        // 更新当前选中的工具
        setCurrentTool(shape);

        // 如果点击的是画笔
        if (shape === 'brush') {
            // 如果存在画笔引用
            if (brushRef.current) {
                // 启用画笔模式
                brushRef.current.start();
            }
            return;
        }

        // 如果点击的是图片
        if (shape === 'image') {
            // 触发文件选择器点击
            if (fileInputRef.current) {
                fileInputRef.current.click();
            }
            return;
        }

        // 如果不是画笔，确保画笔模式被停止
        if (brushRef.current) {
            brushRef.current.stop();
        }

        // 获取画布尺寸
        const canvasWidth = fabricCanvas.width;
        const canvasHeight = fabricCanvas.height;

        // 根据选择的图形创建不同的对象
        let newShape;

        switch (shape) {
            case 'circle':
                newShape = circlePool.acquire();
                newShape.set({
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    fill: '#ff6b81',
                    stroke: '#000000',
                    strokeWidth: 1,
                    visible: true
                });
                break;
            case 'ellipse':
                newShape = ellipsePool.acquire();
                newShape.set({
                    rx: 75,
                    ry: 50,
                    fill: '#3498db',
                    left: canvasWidth / 2 - 75,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'square':
                newShape = new Rect({
                    width: 100,
                    height: 100,
                    fill: '#2ecc71',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    canvas: fabricCanvas
                });
                break;
            case 'rectangle':
                newShape = rectPool.acquire();
                newShape.set({
                    width: 150,
                    height: 100,
                    fill: '#f1c40f',
                    left: canvasWidth / 2 - 75,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'triangle':
                newShape = trianglePool.acquire();
                newShape.set({
                    width: 100,
                    height: 100,
                    fill: '#9b59b6',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'pentagon':
                newShape = pentagonPool.acquire();
                newShape.set({
                    fill: '#e74c3c',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'hexagon':
                newShape = hexagonPool.acquire();
                newShape.set({
                    fill: '#1abc9c',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'star':
                newShape = starPool.acquire();
                newShape.set({
                    fill: '#f39c12',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'diamond':
                newShape = diamondPool.acquire();
                newShape.set({
                    fill: '#8e44ad',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'trapezoid':
                newShape = trapezoidPool.acquire();
                newShape.set({
                    fill: '#16a085',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'parallelogram':
                newShape = parallelogramPool.acquire();
                newShape.set({
                    fill: '#c0392b',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'arrow':
                newShape = arrowPool.acquire();
                newShape.set({
                    fill: '#27ae60',
                    left: canvasWidth / 2 - 50,
                    top: canvasHeight / 2 - 50,
                    visible: true
                });
                break;
            case 'text':
                newShape = new Text({
                    canvas: fabricCanvas,
                    left: canvasWidth / 2 - 150,
                    top: canvasHeight / 2 - 50
                });
                break;
            default:
                return;
        }

        if (newShape) {
            fabricCanvas.add(newShape);
            fabricCanvas.setActiveObject(newShape);

            // 发送到远程
            if (collaborationRef.current?.wsProvider) {
                collaborationRef.current.wsProvider.awareness.setLocalStateField('canvasObject', {
                    type: 'object:added',
                    data: newShape.toJSON(),
                    timestamp: Date.now()
                });
            }

            fabricCanvas.requestRenderAll();
        }
    };

    // 处理背景颜色变化
    const handleBackgroundColorChange = (color) => {
        if (!fabricRef.current) return;

        const activeObject = fabricRef.current.getActiveObject();

        if (activeObject && activeObject.type === 'activeSelection') {
            // 记录组合信息
            const objects = activeObject.getObjects();
            const groupProps = {
                left: activeObject.left,
                top: activeObject.top,
                angle: activeObject.angle,
                scaleX: activeObject.scaleX,
                scaleY: activeObject.scaleY
            };

            // 直接访问协作系统
            const collaboration = collaborationRef.current;
            const sharedObjects = collaboration?.sharedObjects;
            const userId = localStorage.getItem('userId') || 'anonymous';

            if (!sharedObjects) {
                console.error('无法访问共享对象');
                return;
            }

            // 临时解散组合
            fabricRef.current.discardActiveObject();

            // 修改每个对象颜色并同步
            objects.forEach((obj) => {
                if (!obj.id) {
                    obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                }

                // 设置颜色
                obj.set('fill', color);
                if (obj.type === 'text' || obj.type === 'textbox' || obj.type === 'i-text') {
                    obj.set('backgroundColor', color);
                }

                // 确保对象位置正确
                obj.setCoords();

                // 直接同步到远程
                const objData = obj.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: obj.id,
                    type: obj.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: userId
                });
                sharedObjects.set(obj.id, serializedObj);
            });

            // 重要：强制触发远程更新
            if (collaboration.updateCanvasFromSharedObjects) {
                // 标记为不更新远程，避免循环
                const wasUpdating = collaboration.isUpdatingFromRemote;
                collaboration.isUpdatingFromRemote = true;

                // 手动触发一次远程数据更新
                setTimeout(() => {
                    collaboration.updateCanvasFromSharedObjects();
                    collaboration.isUpdatingFromRemote = wasUpdating;

                    // 重建组合，确保所有对象都在组合内
                    const newSelection = new fabric.ActiveSelection(objects, {
                        canvas: fabricRef.current
                    });

                    // 恢复组合属性
                    newSelection.set(groupProps);
                    fabricRef.current.setActiveObject(newSelection);

                    newSelection.setCoords();

                    // 最终渲染
                    fabricRef.current.requestRenderAll();
                }, 50);
            } else {
                // 如果没有更新函数，仍然重建组合
                const newSelection = new fabric.ActiveSelection(objects, {
                    canvas: fabricRef.current
                });
                newSelection.set(groupProps);
                fabricRef.current.setActiveObject(newSelection);
                newSelection.setCoords();
                fabricRef.current.requestRenderAll();
            }
        } else if (activeObject) {
            // 单个对象处理...
            activeObject.set('fill', color);
            if (
                activeObject.type === 'text' ||
                activeObject.type === 'textbox' ||
                activeObject.type === 'i-text'
            ) {
                activeObject.set('backgroundColor', color);
            }

            // 直接同步单个对象
            const collaboration = collaborationRef.current;
            if (collaboration?.sharedObjects) {
                const objData = activeObject.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: activeObject.id || `obj_${Date.now()}`,
                    type: activeObject.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: localStorage.getItem('userId') || 'anonymous'
                });
                collaboration.sharedObjects.set(activeObject.id, serializedObj);

                // 强制更新远程
                if (collaboration.updateCanvasFromSharedObjects) {
                    setTimeout(() => collaboration.updateCanvasFromSharedObjects(), 50);
                }
            }

            fabricRef.current.requestRenderAll();
        }
    };
    // 处理边框宽度变化
    const handleBorderWidthChange = (width) => {
        if (!fabricRef.current) return;

        const activeObject = fabricRef.current.getActiveObject();

        if (activeObject && activeObject.type === 'activeSelection') {
            // 记录组合信息
            const objects = activeObject.getObjects();
            const groupProps = {
                left: activeObject.left,
                top: activeObject.top,
                angle: activeObject.angle,
                scaleX: activeObject.scaleX,
                scaleY: activeObject.scaleY
            };

            // 直接访问协作系统
            const collaboration = collaborationRef.current;
            const sharedObjects = collaboration?.sharedObjects;
            const userId = localStorage.getItem('userId') || 'anonymous';

            if (!sharedObjects) {
                console.error('无法访问共享对象');
                return;
            }

            // 临时解散组合
            fabricRef.current.discardActiveObject();

            // 修改每个对象的边框宽度并同步
            objects.forEach((obj) => {
                if (!obj.id) {
                    obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                }

                // 设置边框宽度
                obj.set('strokeWidth', width);

                // 确保对象位置正确
                obj.setCoords();

                // 直接同步到远程
                const objData = obj.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: obj.id,
                    type: obj.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: userId
                });
                sharedObjects.set(obj.id, serializedObj);
            });

            // 重要：强制触发远程更新
            if (collaboration.updateCanvasFromSharedObjects) {
                // 标记为不更新远程，避免循环
                const wasUpdating = collaboration.isUpdatingFromRemote;
                collaboration.isUpdatingFromRemote = true;

                // 手动触发一次远程数据更新
                setTimeout(() => {
                    collaboration.updateCanvasFromSharedObjects();
                    collaboration.isUpdatingFromRemote = wasUpdating;

                    // 重建组合，确保所有对象都在组合内
                    const newSelection = new fabric.ActiveSelection(objects, {
                        canvas: fabricRef.current
                    });

                    // 恢复组合属性
                    newSelection.set(groupProps);
                    fabricRef.current.setActiveObject(newSelection);

                    // 更新组合坐标
                    newSelection.setCoords();

                    // 最终渲染
                    fabricRef.current.requestRenderAll();
                }, 50);
            } else {
                // 如果没有更新函数，仍然重建组合
                const newSelection = new fabric.ActiveSelection(objects, {
                    canvas: fabricRef.current
                });
                newSelection.set(groupProps);
                fabricRef.current.setActiveObject(newSelection);
                newSelection.setCoords();
                fabricRef.current.requestRenderAll();
            }
        } else if (activeObject) {
            // 单个对象处理保持不变
            activeObject.set('strokeWidth', width);
            activeObject.setCoords();

            // 直接同步单个对象
            const collaboration = collaborationRef.current;
            if (collaboration?.sharedObjects) {
                const objData = activeObject.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: activeObject.id || `obj_${Date.now()}`,
                    type: activeObject.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: localStorage.getItem('userId') || 'anonymous'
                });
                collaboration.sharedObjects.set(activeObject.id, serializedObj);

                // 强制更新远程
                if (collaboration.updateCanvasFromSharedObjects) {
                    setTimeout(() => collaboration.updateCanvasFromSharedObjects(), 50);
                }
            }

            fabricRef.current.requestRenderAll();
        }
    };

    // 处理边框颜色变化
    const handleBorderColorChange = (color) => {
        if (!fabricRef.current) return;

        const activeObject = fabricRef.current.getActiveObject();

        if (activeObject && activeObject.type === 'activeSelection') {
            // 记录组合信息
            const objects = activeObject.getObjects();
            const groupProps = {
                left: activeObject.left,
                top: activeObject.top,
                angle: activeObject.angle,
                scaleX: activeObject.scaleX,
                scaleY: activeObject.scaleY
            };

            // 直接访问协作系统
            const collaboration = collaborationRef.current;
            const sharedObjects = collaboration?.sharedObjects;
            const userId = localStorage.getItem('userId') || 'anonymous';

            if (!sharedObjects) {
                console.error('无法访问共享对象');
                return;
            }

            // 临时解散组合
            fabricRef.current.discardActiveObject();

            // 修改每个对象的边框颜色并同步
            objects.forEach((obj) => {
                if (!obj.id) {
                    obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                }

                // 设置边框颜色
                obj.set({
                    stroke: color,
                    cornerColor: color,
                    borderColor: color
                });

                // 如果是文本对象，还需要更新其边框颜色
                if (obj.type === 'text' || obj.type === 'textbox' || obj.type === 'i-text') {
                    obj.set('borderColor', color);
                }

                // 确保对象位置正确
                obj.setCoords();

                // 直接同步到远程
                const objData = obj.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: obj.id,
                    type: obj.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: userId
                });
                sharedObjects.set(obj.id, serializedObj);
            });

            // 重要：强制触发远程更新
            if (collaboration.updateCanvasFromSharedObjects) {
                // 标记为不更新远程，避免循环
                const wasUpdating = collaboration.isUpdatingFromRemote;
                collaboration.isUpdatingFromRemote = true;

                // 手动触发一次远程数据更新
                setTimeout(() => {
                    collaboration.updateCanvasFromSharedObjects();
                    collaboration.isUpdatingFromRemote = wasUpdating;

                    // 重建组合，确保所有对象都在组合内
                    const newSelection = new fabric.ActiveSelection(objects, {
                        canvas: fabricRef.current
                    });

                    // 恢复组合属性
                    newSelection.set(groupProps);
                    fabricRef.current.setActiveObject(newSelection);

                    // 更新组合坐标
                    newSelection.setCoords();

                    // 最终渲染
                    fabricRef.current.requestRenderAll();
                }, 50);
            } else {
                // 如果没有更新函数，仍然重建组合
                const newSelection = new fabric.ActiveSelection(objects, {
                    canvas: fabricRef.current
                });
                newSelection.set(groupProps);
                fabricRef.current.setActiveObject(newSelection);
                newSelection.setCoords();
                fabricRef.current.requestRenderAll();
            }
        } else if (activeObject) {
            // 单个对象处理保持不变
            activeObject.set({
                stroke: color,
                cornerColor: color,
                borderColor: color
            });

            // 如果是文本对象，还需要更新其边框颜色
            if (
                activeObject.type === 'text' ||
                activeObject.type === 'textbox' ||
                activeObject.type === 'i-text'
            ) {
                activeObject.set('borderColor', color);
            }

            activeObject.setCoords();

            // 直接同步单个对象
            const collaboration = collaborationRef.current;
            if (collaboration?.sharedObjects) {
                const objData = activeObject.toJSON(['id']);
                const serializedObj = JSON.stringify({
                    id: activeObject.id || `obj_${Date.now()}`,
                    type: activeObject.type || 'unknown',
                    objData: objData,
                    timestamp: Date.now(),
                    userId: localStorage.getItem('userId') || 'anonymous'
                });
                collaboration.sharedObjects.set(activeObject.id, serializedObj);

                // 强制更新远程
                if (collaboration.updateCanvasFromSharedObjects) {
                    setTimeout(() => collaboration.updateCanvasFromSharedObjects(), 50);
                }
            }

            fabricRef.current.requestRenderAll();
        }
    };
    // 处理图片上传
    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (!file || !fabricRef.current) return;

        // 创建 Worker
        const imageWorker = new Worker(new URL('../../workers/imageWorker.js', import.meta.url));

        // 获取画布尺寸
        const canvasWidth = fabricRef.current.width;
        const canvasHeight = fabricRef.current.height;

        // 向 Worker 发送数据
        imageWorker.postMessage({
            file,
            canvasWidth,
            canvasHeight
        });

        // 处理 Worker 返回的结果
        imageWorker.onmessage = (event) => {
            const { success, imgUrl, width, height, originalWidth, originalHeight, error } = event.data;

            if (success) {
                // 使用 fabric.Image.fromURL 加载图片
                fabric.Image.fromURL(imgUrl, (img) => {
                    if (!img) {
                        console.error('Failed to load image');
                        return;
                    }

                    // 设置图片位置在画布中心
                    img.set({
                        left: canvasWidth / 2,
                        top: canvasHeight / 2,
                        originX: 'center',
                        originY: 'center',
                        // 确保图片有唯一ID
                        id: `img_${Date.now()}_${Math.floor(Math.random() * 1000)}`
                    });

                    // 计算缩放比例
                    const scaleX = width / originalWidth;
                    const scaleY = height / originalHeight;
                    
                    // 应用缩放
                    img.scaleX = scaleX;
                    img.scaleY = scaleY;

                    // 将图片添加到画布
                    fabricRef.current.add(img);
                    fabricRef.current.setActiveObject(img);
                    fabricRef.current.centerObject(img);

                    // 记录图片信息
                    console.log('添加图片:', img.id, img.type, '尺寸:', width, height, '缩放:', scaleX, scaleY);

                    // 手动触发对象添加事件，确保协同系统能捕获到
                    fabricRef.current.fire('object:added', { target: img });
                    fabricRef.current.fire('object:modified', { target: img });

                    throttledRenderAll();

                    // 触发导入成功事件
                    const successEvent = new CustomEvent('import-success');
                    document.dispatchEvent(successEvent);
                }, {
                    crossOrigin: 'anonymous'
                });
            } else {
                console.error('Image processing failed:', error);
                // 触发导入失败事件
                const failEvent = new CustomEvent('import-fail');
                document.dispatchEvent(failEvent);
            }

            // 终止 Worker
            imageWorker.terminate();
        };

        // 处理 Worker 错误
        imageWorker.onerror = (error) => {
            console.error('Worker error:', error);
            // 触发导入失败事件
            const failEvent = new CustomEvent('import-fail');
            document.dispatchEvent(failEvent);
            // 终止 Worker
            imageWorker.terminate();
        };

        // 重置文件输入，以便可以重新选择相同的文件
        e.target.value = '';
    };

    // 导出画布为图片
    const exportCanvas = () => {
        if (!fabricRef.current) return;

        try {
            // 获取画布数据URL (PNG格式)
            const dataURL = fabricRef.current.toDataURL({
                format: 'png',
                quality: 1
            });

            // 创建下载链接
            const link = document.createElement('a');
            link.download = `${canvasTitle || 'canvas'}-${new Date().getTime()}.png`;
            link.href = dataURL;

            // 触发下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // 触发导出成功事件
            const successEvent = new CustomEvent('export-success');
            document.dispatchEvent(successEvent);
        } catch (error) {
            console.error('Export failed:', error);
            // 触发导出失败事件
            const failEvent = new CustomEvent('export-fail');
            document.dispatchEvent(failEvent);
        }
    };

    // 处理图形置顶
    const handleBringToFront = () => {
        if (!selectedObjects.length || !fabricRef.current) return;

        // 处理多选情况
        selectedObjects.forEach((obj) => {
            if (typeof obj.bringToFront === 'function') {
                obj.bringToFront();
            } else {
                fabricRef.current.bringToFront(obj);
            }
        });

        // 手动触发对象修改事件以确保协同同步
        if (selectedObjects.length === 1) {
            fabricRef.current.fire('object:modified', { target: selectedObjects[0] });
        } else if (selectedObjects.length > 1) {
            // 对于多选情况，逐个触发事件
            selectedObjects.forEach((obj) => {
                fabricRef.current.fire('object:modified', { target: obj });
            });
        }

        throttledRenderAll();
    };

    // 处理图形置底
    const handleSendToBack = () => {
        if (!selectedObjects.length || !fabricRef.current) return;

        // 处理多选情况
        selectedObjects.forEach((obj) => {
            if (typeof obj.sendToBack === 'function') {
                obj.sendToBack();
            } else {
                fabricRef.current.sendToBack(obj);
            }
        });

        // 手动触发对象修改事件以确保协同同步
        if (selectedObjects.length === 1) {
            fabricRef.current.fire('object:modified', { target: selectedObjects[0] });
        } else if (selectedObjects.length > 1) {
            // 对于多选情况，逐个触发事件
            selectedObjects.forEach((obj) => {
                fabricRef.current.fire('object:modified', { target: obj });
            });
        }

        throttledRenderAll();
    };

    // 处理文本属性修改
    const handleTextAttributeChange = (attribute, value) => {
        console.log('handleTextAttributeChange called:', attribute, value);

        if (!selectedObjects.length || !fabricRef.current) {
            console.log('No selected objects or canvas');
            return;
        }

        const selectedObject = selectedObjects[0];

        // 只处理文本对象
        if (
            selectedObject.type !== 'textbox' &&
            selectedObject.type !== 'i-text' &&
            selectedObject.type !== 'text'
        ) {
            console.log('Selected object is not a text object:', selectedObject.type);
            return;
        }

        console.log(
            'Selected text object:',
            selectedObject.type,
            'isEditing:',
            selectedObject.isEditing
        );
        console.log('Selection:', selectedObject.selectionStart, selectedObject.selectionEnd);

        // 如果正在编辑且有选中的文本，则只更新选中文本的样式
        if (
            selectedObject.isEditing &&
            selectedObject.selectionStart !== selectedObject.selectionEnd
        ) {
            console.log(
                'Applying style to selected text from:',
                selectedObject.selectionStart,
                'to:',
                selectedObject.selectionEnd
            );

            try {
                // 创建样式对象
                const style = {};

                // 处理背景色特殊情况
                if (attribute === 'backgroundColor') {
                    style['textBackgroundColor'] = value;
                } else {
                    style[attribute] = value;
                }

                // 应用样式到选中文本
                selectedObject.setSelectionStyles(style);
                console.log('Applied style to selected text:', style);
            } catch (error) {
                console.error('Error applying style to selected text:', error);
                // 如果失败，回退到直接设置整个文本对象的样式
                selectedObject.set(attribute, value);
            }
        } else {
            // 否则更新整个文本对象的样式
            console.log('Updating whole text style');

            // 处理背景色特殊情况
            if (attribute === 'backgroundColor') {
                selectedObject.set('textBackgroundColor', value);
            } else {
                selectedObject.set(attribute, value);

                // 如果是改变文字颜色，同时更新控制点颜色
                if (attribute === 'fill') {
                    selectedObject.set({
                        cornerColor: value,
                        borderColor: value
                    });
                }
            }
        }

        // 手动触发对象修改事件以确保协同同步
        fabricRef.current.fire('object:modified', { target: selectedObject });

        throttledRenderAll();
    };

    // Zoom state and handlers
    const [zoom, setZoom] = useState(1.0);

    const handleZoomChange = (value) => {
        console.log('Zoom change requested:', value);
        const fabricCanvas = fabricRef.current;
        if (!fabricCanvas) {
            console.error('Fabric canvas not initialized');
            return;
        }

        // 确保缩放值在0.1-3.0范围内
        const clampedValue = Math.max(0.1, Math.min(3.0, value));
        setZoom(clampedValue);
        console.log('Setting fabric zoom to:', clampedValue);
        fabricCanvas.setZoom(clampedValue);
        throttledRenderAll();
        console.log('Zoom updated successfully');
    };

    const handleResetZoom = () => {
        handleZoomChange(1.0);
    };

    // 渲染优化 - 使用requestAnimationFrame
    const renderRequestRef = useRef(null);
    const needsRenderRef = useRef(false);

    const renderAllRef = useRef(() => {
        if (fabricRef.current) {
            fabricRef.current.requestRenderAll();
            needsRenderRef.current = false;
        }
    });

    const scheduleRender = useCallback(() => {
        if (!needsRenderRef.current) {
            needsRenderRef.current = true;
            renderRequestRef.current = requestAnimationFrame(renderAllRef.current);
        }
    }, []);

    // 创建节流版本
    // 使用更宽松的节流时间(200ms)以获得更好的性能
    const throttledRenderAll = useRef(throttle(scheduleRender, 200)).current;

    useEffect(() => {
        const fabricCanvas = fabricRef.current;
        if (!fabricCanvas) return;

        // Set up event listeners
        fabricCanvas.on('object:modified', throttledRenderAll);
        fabricCanvas.on('object:added', throttledRenderAll);
        fabricCanvas.on('object:removed', throttledRenderAll);

        return () => {
            // Clean up event listeners
            fabricCanvas.off('object:modified', throttledRenderAll);
            fabricCanvas.off('object:added', throttledRenderAll);
            fabricCanvas.off('object:removed', throttledRenderAll);

            // 清理动画帧请求
            if (renderRequestRef.current) {
                cancelAnimationFrame(renderRequestRef.current);
            }
        };
    }, []);

    // 在组件卸载时清理 Worker
    useEffect(() => {
        return () => {
            canvasDataWorkerManager.terminate();
        };
    }, []);

    // 处理画布渲染
    const handleCanvasRender = async () => {
        if (!fabricRef.current) return;

        try {
            const objects = fabricRef.current.getObjects().map(obj => ({
                id: obj.id,
                left: obj.left,
                top: obj.top,
                width: obj.width * obj.scaleX,
                height: obj.height * obj.scaleY,
                rotation: obj.angle,
                scale: obj.scaleX
            }));

            const canvasWidth = fabricRef.current.width;
            const canvasHeight = fabricRef.current.height;

            // 使用 Worker 进行渲染计算
            const result = await renderWorkerManager.render(objects, canvasWidth, canvasHeight);

            // 应用计算结果
            result.objects.forEach(processedObj => {
                const originalObj = fabricRef.current.getObjects().find(obj => obj.id === processedObj.id);
                if (originalObj) {
                    // 更新对象位置
                    originalObj.set({
                        left: processedObj.calculatedPosition.x,
                        top: processedObj.calculatedPosition.y
                    });

                    // 应用变换矩阵
                    if (processedObj.transform) {
                        const { a, b, c, d, e, f } = processedObj.transform;
                        originalObj.set({
                            scaleX: Math.sqrt(a * a + b * b),
                            scaleY: Math.sqrt(c * c + d * d),
                            angle: Math.atan2(b, a) * (180 / Math.PI)
                        });
                    }

                    // 处理碰撞
                    if (processedObj.collisions && processedObj.collisions.length > 0) {
                        // 可以在这里处理碰撞，例如高亮显示碰撞的对象
                        console.log(`Object ${processedObj.id} collides with:`, processedObj.collisions);
                    }
                }
            });

            fabricRef.current.requestRenderAll();
        } catch (error) {
            console.error('Render calculation failed:', error);
        }
    };

    // 处理布局计算
    const handleLayoutCalculation = async (layoutType = 'grid') => {
        if (!fabricRef.current) return;

        try {
            const objects = fabricRef.current.getObjects().map(obj => ({
                id: obj.id,
                left: obj.left,
                top: obj.top,
                width: obj.width * obj.scaleX,
                height: obj.height * obj.scaleY
            }));

            const canvasWidth = fabricRef.current.width;
            const canvasHeight = fabricRef.current.height;

            // 使用 Worker 进行布局计算
            const layout = await renderWorkerManager.calculateLayout(
                objects,
                canvasWidth,
                canvasHeight,
                layoutType
            );

            // 应用布局结果
            layout.positions.forEach(pos => {
                const obj = fabricRef.current.getObjects().find(o => o.id === pos.id);
                if (obj) {
                    obj.set({
                        left: pos.x,
                        top: pos.y
                    });
                }
            });

            fabricRef.current.requestRenderAll();
        } catch (error) {
            console.error('Layout calculation failed:', error);
        }
    };

    // 在组件卸载时清理 Worker
    useEffect(() => {
        return () => {
            renderWorkerManager.terminate();
        };
    }, []);

    // 添加自动布局按钮的处理函数
    const handleAutoLayout = () => {
        handleLayoutCalculation('force');
    };

    // 在工具栏中添加自动布局按钮
    const renderToolbar = () => {
        return (
            <div className="toolbar">
                {/* ... existing toolbar items ... */}
                <button
                    onClick={handleAutoLayout}
                    title="自动布局"
                >
                    自动布局
                </button>
            </div>
        );
    };

    return (
        <>
            <>
                <Header
                    selectedCanvas={true}
                    canvasTitle={canvasTitle }
                    onTitleChange={onTitleChange}
                    isEditing={isEditing}
                    id={id}
                />
                <CanvasHeader
                    canvasTitle={canvasTitle || routeTitle}
                    isEditing={isEditing}
                    onTitleChange={onTitleChange}
                    id={id}
                    handleSaveCanvas={handleSaveCanvas}
                    navigate={navigate}
                    isConnected={isConnected}
                    onlineUsers={onlineUsers}
                />
                <div className="canvas-layout">
                    <LeftSide
                        onShapeClick={handleShapeClick}
                        onResetZoom={handleResetZoom}
                        onClearCanvas={handleClearCanvas}
                    />
                    <div className="canvas-right-panel">
                        <div className="canvas-container" onClick={() => navigate(`/canvas/${id}`)}>
                            <div
                                ref={canvasContainerRef}
                                style={{ position: 'relative', width: '100%', height: '100%' }}
                            >
                                <canvas ref={canvasRef} id="fabric-canvas"></canvas>

                                {/* 显示协作状态提示 */}
                                {!isConnected && (
                                    <div
                                        className="collaboration-alert"
                                        style={{
                                            position: 'absolute',
                                            top: '50%',
                                            left: '50%',
                                            transform: 'translate(-50%, -50%)',
                                            padding: '10px',
                                            backgroundColor: 'rgba(255, 0, 0, 0.1)',
                                            border: '1px solid #ff4d4f',
                                            borderRadius: '4px'
                                        }}
                                    >
                                        <p>未连接到协作服务器，请确保服务器已启动</p>
                                        <p>启动命令: npm run simple-server</p>
                                    </div>
                                )}

                                {/* 添加在线用户列表 */}
                                <OnlineUsersList users={onlineUsers} />
                            </div>
                            <div className="floating-toolbar">
                                <Toolbar
                                    onChangeBackgroundColor={handleBackgroundColorChange}
                                    onChangeBorderWidth={handleBorderWidthChange}
                                    onChangeBorderColor={handleBorderColorChange}
                                    onBringToFront={handleBringToFront}
                                    onSendToBack={handleSendToBack}
                                    onDeleteObject={handleDeleteObject}
                                    onResetZoom={handleResetZoom}
                                    selectedObjects={selectedObjects}
                                    onTextAttributeChange={handleTextAttributeChange}
                                    onBrushModeChange={(mode) => brushRef.current?.setMode?.(mode)}
                                    onBrushDottedChange={(isDotted) =>
                                        brushRef.current?.updateProps?.({ isDotted })
                                    }
                                    onDotDensityChange={(density) =>
                                        brushRef.current?.setDotDensity?.(density)
                                    }
                                    isBrushActive={currentTool === 'brush'}
                                    zoom={zoom}
                                    onZoomChange={handleZoomChange}
                                >
                                    <Button
                                        type="primary"
                                        danger
                                        onClick={handleClearCanvas}
                                        style={{ marginLeft: '10px' }}
                                    >
                                        清空画布
                                    </Button>
                                </Toolbar>
                            </div>
                            {/* 隐藏的文件输入，用于图片上传 */}
                            <input
                                type="file"
                                ref={fileInputRef}
                                style={{ display: 'none' }}
                                onChange={handleImageUpload}
                                accept="image/*"
                            />
                        </div>
                    </div>
                </div>
            </>
        </>
    );
};

export { Canvas };
